import React, { useState } from 'react';
import { Globe, Save, RotateCcw, TestTube, Trash2, RefreshCw, BarChart3, Activity } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';

const CacheConfig = ({ toggleSidebar }) => {
  // 缓存策略配置
  const [cacheStrategy, setCacheStrategy] = useState({
    defaultTTL: 3600,
    maxMemoryUsage: 512, // MB
    evictionPolicy: 'lru',
    enableCompression: true,
    compressionLevel: 6,
    enablePersistence: true,
    persistenceInterval: 300,
    enableCluster: false,
    clusterNodes: 3
  });

  // 缓存规则配置
  const [cacheRules, setCacheRules] = useState([
    {
      id: 1,
      name: '用户会话',
      pattern: 'session:*',
      ttl: 1800,
      enabled: true,
      description: '用户登录会话缓存'
    },
    {
      id: 2,
      name: '文件元数据',
      pattern: 'file:meta:*',
      ttl: 7200,
      enabled: true,
      description: '文件元数据信息缓存'
    },
    {
      id: 3,
      name: 'API响应',
      pattern: 'api:response:*',
      ttl: 300,
      enabled: true,
      description: 'API接口响应缓存'
    },
    {
      id: 4,
      name: '数据库查询',
      pattern: 'db:query:*',
      ttl: 600,
      enabled: false,
      description: '数据库查询结果缓存'
    }
  ]);

  // 预热配置
  const [warmupConfig, setWarmupConfig] = useState({
    enabled: true,
    scheduleTime: '02:00',
    warmupUrls: [
      'https://api.example.com/users',
      'https://api.example.com/files/popular',
      'https://api.example.com/system/config'
    ],
    concurrency: 5,
    timeout: 30000
  });

  // 监控配置
  const [monitorConfig, setMonitorConfig] = useState({
    enableMetrics: true,
    metricsInterval: 60,
    enableAlerts: true,
    hitRateThreshold: 80,
    memoryThreshold: 90,
    responseTimeThreshold: 1000,
    alertEmail: 'admin@example.com'
  });

  const evictionPolicies = [
    { value: 'lru', label: 'LRU (最近最少使用)' },
    { value: 'lfu', label: 'LFU (最少使用频率)' },
    { value: 'fifo', label: 'FIFO (先进先出)' },
    { value: 'random', label: 'Random (随机)' },
    { value: 'ttl', label: 'TTL (按过期时间)' }
  ];

  const compressionLevels = [
    { value: 1, label: '1 (最快)' },
    { value: 3, label: '3 (快速)' },
    { value: 6, label: '6 (平衡)' },
    { value: 9, label: '9 (最佳压缩)' }
  ];

  const handleSave = () => {
    const allConfig = {
      strategy: cacheStrategy,
      rules: cacheRules,
      warmup: warmupConfig,
      monitor: monitorConfig
    };
    
    console.log('保存缓存配置:', allConfig);
    alert('缓存配置已保存');
  };

  const handleReset = () => {
    if (confirm('确定要重置所有缓存配置到默认值吗？')) {
      setCacheStrategy({
        defaultTTL: 3600,
        maxMemoryUsage: 512,
        evictionPolicy: 'lru',
        enableCompression: true,
        compressionLevel: 6,
        enablePersistence: true,
        persistenceInterval: 300,
        enableCluster: false,
        clusterNodes: 3
      });
      
      setWarmupConfig({
        enabled: true,
        scheduleTime: '02:00',
        warmupUrls: [
          'https://api.example.com/users',
          'https://api.example.com/files/popular',
          'https://api.example.com/system/config'
        ],
        concurrency: 5,
        timeout: 30000
      });
      
      setMonitorConfig({
        enableMetrics: true,
        metricsInterval: 60,
        enableAlerts: true,
        hitRateThreshold: 80,
        memoryThreshold: 90,
        responseTimeThreshold: 1000,
        alertEmail: 'admin@example.com'
      });
    }
  };

  const handleClearCache = () => {
    if (confirm('确定要清空所有缓存数据吗？此操作不可恢复！')) {
      console.log('清空缓存');
      alert('缓存已清空');
    }
  };

  const handleAddRule = () => {
    const newRule = {
      id: Math.max(...cacheRules.map(r => r.id)) + 1,
      name: '新规则',
      pattern: '*',
      ttl: 3600,
      enabled: true,
      description: ''
    };
    setCacheRules(prev => [...prev, newRule]);
  };

  const handleDeleteRule = (ruleId) => {
    setCacheRules(prev => prev.filter(rule => rule.id !== ruleId));
  };

  const handleUpdateRule = (ruleId, field, value) => {
    setCacheRules(prev => prev.map(rule => 
      rule.id === ruleId ? { ...rule, [field]: value } : rule
    ));
  };

  const handleAddWarmupUrl = () => {
    setWarmupConfig(prev => ({
      ...prev,
      warmupUrls: [...prev.warmupUrls, '']
    }));
  };

  const handleUpdateWarmupUrl = (index, value) => {
    setWarmupConfig(prev => ({
      ...prev,
      warmupUrls: prev.warmupUrls.map((url, i) => i === index ? value : url)
    }));
  };

  const handleDeleteWarmupUrl = (index) => {
    setWarmupConfig(prev => ({
      ...prev,
      warmupUrls: prev.warmupUrls.filter((_, i) => i !== index)
    }));
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <Globe className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    缓存配置
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理缓存策略和性能优化
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline" onClick={handleClearCache} className="text-red-600 hover:text-red-700">
                <Trash2 className="w-4 h-4 mr-2" />
                清空缓存
              </Button>
              <Button variant="outline" onClick={handleReset}>
                <RotateCcw className="w-4 h-4 mr-2" />
                重置配置
              </Button>
              <Button onClick={handleSave} className="bg-primary hover:bg-primary-600">
                <Save className="w-4 h-4 mr-2" />
                保存配置
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <Tabs defaultValue="strategy" className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="strategy">缓存策略</TabsTrigger>
            <TabsTrigger value="rules">缓存规则</TabsTrigger>
            <TabsTrigger value="warmup">缓存预热</TabsTrigger>
            <TabsTrigger value="monitor">监控告警</TabsTrigger>
          </TabsList>

          {/* 缓存策略 */}
          <TabsContent value="strategy" className="mt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Globe className="w-5 h-5" />
                    <span>基础策略</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="defaultTTL">默认TTL (秒)</Label>
                    <Input
                      id="defaultTTL"
                      type="number"
                      value={cacheStrategy.defaultTTL}
                      onChange={(e) => setCacheStrategy(prev => ({ ...prev, defaultTTL: parseInt(e.target.value) || 3600 }))}
                    />
                  </div>

                  <div>
                    <Label htmlFor="maxMemoryUsage">最大内存使用 (MB)</Label>
                    <Input
                      id="maxMemoryUsage"
                      type="number"
                      value={cacheStrategy.maxMemoryUsage}
                      onChange={(e) => setCacheStrategy(prev => ({ ...prev, maxMemoryUsage: parseInt(e.target.value) || 512 }))}
                    />
                  </div>

                  <div>
                    <Label htmlFor="evictionPolicy">淘汰策略</Label>
                    <Select value={cacheStrategy.evictionPolicy} onValueChange={(value) => setCacheStrategy(prev => ({ ...prev, evictionPolicy: value }))}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {evictionPolicies.map(policy => (
                          <SelectItem key={policy.value} value={policy.value}>
                            {policy.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="enableCompression">启用压缩</Label>
                      <p className="text-sm text-material-grey-600">压缩缓存数据以节省内存</p>
                    </div>
                    <Switch
                      id="enableCompression"
                      checked={cacheStrategy.enableCompression}
                      onCheckedChange={(checked) => setCacheStrategy(prev => ({ ...prev, enableCompression: checked }))}
                    />
                  </div>

                  {cacheStrategy.enableCompression && (
                    <div>
                      <Label htmlFor="compressionLevel">压缩级别</Label>
                      <Select value={cacheStrategy.compressionLevel.toString()} onValueChange={(value) => setCacheStrategy(prev => ({ ...prev, compressionLevel: parseInt(value) }))}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {compressionLevels.map(level => (
                            <SelectItem key={level.value} value={level.value.toString()}>
                              {level.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Activity className="w-5 h-5" />
                    <span>高级配置</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="enablePersistence">启用持久化</Label>
                      <p className="text-sm text-material-grey-600">定期将缓存数据保存到磁盘</p>
                    </div>
                    <Switch
                      id="enablePersistence"
                      checked={cacheStrategy.enablePersistence}
                      onCheckedChange={(checked) => setCacheStrategy(prev => ({ ...prev, enablePersistence: checked }))}
                    />
                  </div>

                  {cacheStrategy.enablePersistence && (
                    <div>
                      <Label htmlFor="persistenceInterval">持久化间隔 (秒)</Label>
                      <Input
                        id="persistenceInterval"
                        type="number"
                        value={cacheStrategy.persistenceInterval}
                        onChange={(e) => setCacheStrategy(prev => ({ ...prev, persistenceInterval: parseInt(e.target.value) || 300 }))}
                      />
                    </div>
                  )}

                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="enableCluster">启用集群模式</Label>
                      <p className="text-sm text-material-grey-600">使用多节点提高可用性</p>
                    </div>
                    <Switch
                      id="enableCluster"
                      checked={cacheStrategy.enableCluster}
                      onCheckedChange={(checked) => setCacheStrategy(prev => ({ ...prev, enableCluster: checked }))}
                    />
                  </div>

                  {cacheStrategy.enableCluster && (
                    <div>
                      <Label htmlFor="clusterNodes">集群节点数</Label>
                      <Input
                        id="clusterNodes"
                        type="number"
                        min="3"
                        max="10"
                        value={cacheStrategy.clusterNodes}
                        onChange={(e) => setCacheStrategy(prev => ({ ...prev, clusterNodes: parseInt(e.target.value) || 3 }))}
                      />
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* 缓存规则 */}
          <TabsContent value="rules" className="mt-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center space-x-2">
                    <BarChart3 className="w-5 h-5" />
                    <span>缓存规则管理</span>
                  </CardTitle>
                  <Button onClick={handleAddRule} size="sm">
                    <RefreshCw className="w-4 h-4 mr-2" />
                    添加规则
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {cacheRules.map((rule) => (
                    <div key={rule.id} className="border border-material-grey-200 rounded-lg p-4">
                      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                        <div>
                          <Label htmlFor={`rule-name-${rule.id}`}>规则名称</Label>
                          <Input
                            id={`rule-name-${rule.id}`}
                            value={rule.name}
                            onChange={(e) => handleUpdateRule(rule.id, 'name', e.target.value)}
                          />
                        </div>
                        
                        <div>
                          <Label htmlFor={`rule-pattern-${rule.id}`}>匹配模式</Label>
                          <Input
                            id={`rule-pattern-${rule.id}`}
                            value={rule.pattern}
                            onChange={(e) => handleUpdateRule(rule.id, 'pattern', e.target.value)}
                            placeholder="例如: user:*"
                          />
                        </div>
                        
                        <div>
                          <Label htmlFor={`rule-ttl-${rule.id}`}>TTL (秒)</Label>
                          <Input
                            id={`rule-ttl-${rule.id}`}
                            type="number"
                            value={rule.ttl}
                            onChange={(e) => handleUpdateRule(rule.id, 'ttl', parseInt(e.target.value) || 3600)}
                          />
                        </div>
                        
                        <div className="flex items-center space-x-2">
                          <Switch
                            checked={rule.enabled}
                            onCheckedChange={(checked) => handleUpdateRule(rule.id, 'enabled', checked)}
                          />
                          <Badge className={rule.enabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}>
                            {rule.enabled ? '启用' : '禁用'}
                          </Badge>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteRule(rule.id)}
                            className="text-red-600 hover:text-red-700"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                      
                      <div className="mt-3">
                        <Label htmlFor={`rule-desc-${rule.id}`}>描述</Label>
                        <Input
                          id={`rule-desc-${rule.id}`}
                          value={rule.description}
                          onChange={(e) => handleUpdateRule(rule.id, 'description', e.target.value)}
                          placeholder="规则描述"
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 缓存预热 */}
          <TabsContent value="warmup" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <RefreshCw className="w-5 h-5" />
                  <span>缓存预热配置</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex items-center justify-between">
                  <div>
                    <Label htmlFor="warmup-enabled">启用缓存预热</Label>
                    <p className="text-sm text-material-grey-600">定时预加载热点数据到缓存</p>
                  </div>
                  <Switch
                    id="warmup-enabled"
                    checked={warmupConfig.enabled}
                    onCheckedChange={(checked) => setWarmupConfig(prev => ({ ...prev, enabled: checked }))}
                  />
                </div>

                {warmupConfig.enabled && (
                  <div className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div>
                        <Label htmlFor="scheduleTime">执行时间</Label>
                        <Input
                          id="scheduleTime"
                          type="time"
                          value={warmupConfig.scheduleTime}
                          onChange={(e) => setWarmupConfig(prev => ({ ...prev, scheduleTime: e.target.value }))}
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="concurrency">并发数</Label>
                        <Input
                          id="concurrency"
                          type="number"
                          min="1"
                          max="20"
                          value={warmupConfig.concurrency}
                          onChange={(e) => setWarmupConfig(prev => ({ ...prev, concurrency: parseInt(e.target.value) || 5 }))}
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="timeout">超时时间 (毫秒)</Label>
                        <Input
                          id="timeout"
                          type="number"
                          value={warmupConfig.timeout}
                          onChange={(e) => setWarmupConfig(prev => ({ ...prev, timeout: parseInt(e.target.value) || 30000 }))}
                        />
                      </div>
                    </div>

                    <div>
                      <div className="flex items-center justify-between mb-3">
                        <Label>预热URL列表</Label>
                        <Button onClick={handleAddWarmupUrl} size="sm" variant="outline">
                          添加URL
                        </Button>
                      </div>
                      <div className="space-y-2">
                        {warmupConfig.warmupUrls.map((url, index) => (
                          <div key={index} className="flex items-center space-x-2">
                            <Input
                              value={url}
                              onChange={(e) => handleUpdateWarmupUrl(index, e.target.value)}
                              placeholder="https://api.example.com/endpoint"
                            />
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDeleteWarmupUrl(index)}
                              className="text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* 监控告警 */}
          <TabsContent value="monitor" className="mt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <BarChart3 className="w-5 h-5" />
                    <span>性能监控</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="enableMetrics">启用性能监控</Label>
                      <p className="text-sm text-material-grey-600">收集缓存性能指标</p>
                    </div>
                    <Switch
                      id="enableMetrics"
                      checked={monitorConfig.enableMetrics}
                      onCheckedChange={(checked) => setMonitorConfig(prev => ({ ...prev, enableMetrics: checked }))}
                    />
                  </div>

                  {monitorConfig.enableMetrics && (
                    <div>
                      <Label htmlFor="metricsInterval">监控间隔 (秒)</Label>
                      <Input
                        id="metricsInterval"
                        type="number"
                        min="10"
                        max="3600"
                        value={monitorConfig.metricsInterval}
                        onChange={(e) => setMonitorConfig(prev => ({ ...prev, metricsInterval: parseInt(e.target.value) || 60 }))}
                      />
                    </div>
                  )}
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Activity className="w-5 h-5" />
                    <span>告警配置</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="enableAlerts">启用告警</Label>
                      <p className="text-sm text-material-grey-600">当指标异常时发送告警</p>
                    </div>
                    <Switch
                      id="enableAlerts"
                      checked={monitorConfig.enableAlerts}
                      onCheckedChange={(checked) => setMonitorConfig(prev => ({ ...prev, enableAlerts: checked }))}
                    />
                  </div>

                  {monitorConfig.enableAlerts && (
                    <div className="space-y-4">
                      <div>
                        <Label htmlFor="hitRateThreshold">命中率阈值 (%)</Label>
                        <Input
                          id="hitRateThreshold"
                          type="number"
                          min="0"
                          max="100"
                          value={monitorConfig.hitRateThreshold}
                          onChange={(e) => setMonitorConfig(prev => ({ ...prev, hitRateThreshold: parseInt(e.target.value) || 80 }))}
                        />
                      </div>

                      <div>
                        <Label htmlFor="memoryThreshold">内存使用阈值 (%)</Label>
                        <Input
                          id="memoryThreshold"
                          type="number"
                          min="0"
                          max="100"
                          value={monitorConfig.memoryThreshold}
                          onChange={(e) => setMonitorConfig(prev => ({ ...prev, memoryThreshold: parseInt(e.target.value) || 90 }))}
                        />
                      </div>

                      <div>
                        <Label htmlFor="responseTimeThreshold">响应时间阈值 (毫秒)</Label>
                        <Input
                          id="responseTimeThreshold"
                          type="number"
                          value={monitorConfig.responseTimeThreshold}
                          onChange={(e) => setMonitorConfig(prev => ({ ...prev, responseTimeThreshold: parseInt(e.target.value) || 1000 }))}
                        />
                      </div>

                      <div>
                        <Label htmlFor="alertEmail">告警邮箱</Label>
                        <Input
                          id="alertEmail"
                          type="email"
                          value={monitorConfig.alertEmail}
                          onChange={(e) => setMonitorConfig(prev => ({ ...prev, alertEmail: e.target.value }))}
                        />
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </>
  );
};

export default CacheConfig;
